package com.hddznet.uniplatform.sm.config.cas;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

public class CasUserDetailsAuthenticationProvider implements AuthenticationProvider {

	private CasUserDetailsService casUserDetailsService;
	
	public CasUserDetailsAuthenticationProvider(CasUserDetailsService casUserDetailsService) {
		this.casUserDetailsService = casUserDetailsService;
	}
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		CasAuthenticationToken authenticationToken = (CasAuthenticationToken) authentication;
		
		UserDetails userDetails = casUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
		//不通过
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("Unable to obtain user information");
        }
        //通过
        return authenticationToken;
	}	

	/**
	 * 根据token类型，来判断使用哪个Provider
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return CasAuthenticationToken.class.isAssignableFrom(authentication);
	}

}